var stats = new Stats(),
    c = document.getElementById('c'),
    ctx = c.getContext('2d');

window.addEventListener('resize', handleWindowResize, false);
function handleWindowResize () {
    c.width = window.innerWidth * window.devicePixelRatio;
    c.height = window.innerHeight * window.devicePixelRatio;
}
handleWindowResize();

var GRAVITY_FORCE = 9.81, //自然重力 9.81m/s^2
    PLANT_HEIGHT = 10, //平台高度 10M
    //表示 屏幕上 每50个像素为一米
    //这一步的价值在于，之后的所有关于距离的单位，都可以采用现实中的单位————米，来表示。
    //通过此属性换算成像素数，在屏幕上展示
    PIXEL_PER_METER = (c.height - 150) / PLANT_HEIGHT,
    animationFrameId,
    fps;

/**
 * 圆球下落
 */
function Ball (x, y, r) {
    Vector.call(this, x, y);
    this.r = r || 10;
    this.speed = new Vector();
}
Ball.prototype = (function (o) {
    var v = new Vector(0, 0);
    for(var p in o) {
        v[p] = o[p];
    }
    return v;
})({
    update: function (ctx, time) {
        time = time || 0;
        this.speed.set({
            x: 0,
            // 先算出 速度，单位为：px/s，每秒多少像素
            y: GRAVITY_FORCE * time / 1000 * PIXEL_PER_METER
        });
        //除以 fps 将px/s 转换成 px/f
        // console.log(this.speed.y);
        this.y += this.speed.y / fps;
        if(this.y + this.r >= c.height) {
            this.y = c.height - this.r;
            var endTime = +new Date();
            cancelAnimationFrame(animationFrameId);
            console.log((endTime - startTime) / 1000);
        }
        this.draw(ctx);
    },
    draw: function (ctx) {
        ctx.save();
        ctx.fillStyle = 'red';
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
        ctx.closePath();
        ctx.fill();
        ctx.restore();
    }
})

var ball = new Ball(c.width / 2, 100, 50);
var startTime = +new Date();

(function loop(time) {
    ctx.clearRect(0, 0, c.width, c.height);
    animationFrameId = requestAnimationFrame(loop);
    var curFps = stats.update()
    fps = curFps === 0 ? 60 : curFps;
    ball.update(ctx, time);
})();